#region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;

using Osh.Data;
using Osh.Epg;
using Osh.Media;

namespace Osh.Dvb
{
	/// <summary>
	/// Summary description for EpgProvider.
	/// </summary>
	public class EpgProvider : IEpgProvider
	{
		private DataContext _dataContext;

		public EpgProvider()
		{
			_dataContext = new DataContext();
		}

		public ChannelEpg GetChannelEpg(IChannel channel, DateTime startTime, DateTime endTime)
		{
			IDvbChannel dvbChannel = channel as IDvbChannel;
			if(dvbChannel == null)
				return new ChannelEpg(startTime, endTime);

			int transportId = dvbChannel.TransportId;
			int networkId = dvbChannel.NetworkId;
			int serviceId = dvbChannel.ServiceId;

			using(IDataReader reader = _dataContext.GetEpgEvents(transportId, networkId, serviceId,
					  startTime.ToUniversalTime(), endTime.ToUniversalTime()))
			{
				List<EpgEvent> events = new List<EpgEvent>();
				string lastEventLanguage = null;
				while(reader.Read())
				{
					DateTime eventStartTime = reader.GetDateTime(reader.GetOrdinal("StartTime")).ToLocalTime();
					DateTime eventEndTime = reader.GetDateTime(reader.GetOrdinal("EndTime")).ToLocalTime();
					string name = reader.GetString(reader.GetOrdinal("EventName"));
					string description = reader.GetString(reader.GetOrdinal("Text"));
					string language = reader.GetString(reader.GetOrdinal("Language"));

					if(lastEventLanguage != null && language != lastEventLanguage)
					{
						if(Osh.Configuration.Configuration.Current.Osh.Epg.IsLanguageMorePrefered(language, lastEventLanguage))
						{
							events.Clear();
						}
						else
							continue;
					}

					EpgEvent epgEvent = new EpgEvent(eventStartTime, eventEndTime, language, name, description);
					events.Add(epgEvent);

					lastEventLanguage = language;
				}
				return new ChannelEpg(startTime, endTime, events);
			}
		}
	}
}
